package mongo

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/cgs/app/models"
	v1 "cgs-server/server/cgs/app/models/v1"
	"cgs-server/server/cgs/app/store"
	"cgs-server/server/model"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type worksheetView struct {
	db             *helper.Mongo
	collectionName string
}

func (w *worksheetView) DeleteMany(wg *models.WorksheetView, user *model.User, opts v1.DeleteOptions) error {
	filter := opts.GetFilter()
	if len(filter) == 0 {
		return nil
	}
	//wg.ResolveFilter(wg, user, &filter)
	_, err := w.db.DeleteMany(w.collectionName, filter)
	return err
}

func (w *worksheetView) Save(wg *models.WorksheetView, user *model.User, opts v1.CreateOptions) error {
	if wg.Id.IsZero() {
		wg.Id = primitive.NewObjectID()
	}
	_, err := w.db.InsertOne(w.collectionName, wg)
	return err
}

func (w *worksheetView) Get(wg *models.WorksheetView, user *model.User, opts v1.GetOptions) (*models.WorksheetView, error) {
	filter := bson.M{}
	if !wg.Id.IsZero() {
		filter["id"] = wg.Id
	}
	result := &models.WorksheetView{}
	find, err := w.db.FindOne(w.collectionName, filter, result)
	if !find {
		return nil, fmt.Errorf("worksheet view not found: %s", wg.Id.Hex())
	}
	return result, err
}

func (w *worksheetView) Update(wg *models.WorksheetView, user *model.User, opts v1.UpdateOptions) error {
	filter := bson.M{}
	if !wg.Id.IsZero() {
		filter["id"] = wg.Id
	} else {
		return fmt.Errorf("id is required")
	}
	set := bson.M{}
	if wg.Name != "" {
		set["name"] = wg.Name
	}
	if wg.ViewType != nil {
		set["viewType"] = wg.ViewType
	}
	//wg.ResolveUpdateCondition(wg, user, &set)
	update := bson.M{
		"$set": set,
	}
	_, err := w.db.UpdateOne(w.collectionName, filter, update)
	return err
}

func (w *worksheetView) Delete(wg *models.WorksheetView, user *model.User, opts v1.DeleteOptions) error {
	filter := bson.M{}
	if !wg.Id.IsZero() {
		filter["id"] = wg.Id
	}
	//wg.ResolveFilter(wg, user, &filter)
	_, err := w.db.DeleteOne(w.collectionName, filter)
	return err
}

func (w *worksheetView) List(wg *models.WorksheetView, user *model.User, opts v1.ListOptions) (*models.WorksheetViewList, error) {
	filter := opts.GetFilter()
	//wg.ResolveFilter(wg, user, &filter)
	results := &models.WorksheetViewList{}
	err := w.db.FindMany(w.collectionName, filter, results, opts.ResolveFindOptions())
	return results, err
}

func newWorksheetViewStore(d *datastore) store.WorksheetViewStore {
	return &worksheetView{
		db:             d.db,
		collectionName: server.WorksheetViewCollectionName,
	}
}
